package com.token.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther: henriy
 * @Date: 2023/12/5
 */
@Slf4j
public class AesUtil {
    // 长度只能是16位，24位，32位
    private static final String defaultKey = "1234567891011123";

    public static String encryptBase64(String content,String key){
        try{
            byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),
                    key.getBytes()).getEncoded();
            SymmetricCrypto aes = SecureUtil.aes(byteKey);
            // 加密
            return aes.encryptBase64(content);
        }catch (Exception e){
            log.error(" 加密异常:{}",e.getMessage());
        }

        return null;
    }

    public static String decryptStr(String encryptString,String key){
        try{
            byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),
                    key.getBytes()).getEncoded();
            SymmetricCrypto aes = SecureUtil.aes(byteKey);
            //解密
            return aes.decryptStr(encryptString);
        }catch (Exception e){
            log.error(" 解密异常:{}",e.getMessage());
        }

        return null;
    }

    public static void main(String[] args) {
        // 16位自定义密码
        String key = "1234567891011123";
        String content = "明文";
        String encryptStr = encryptBase64(content,key);
        System.out.println(encryptStr);
        System.out.println(decryptStr(encryptStr,key));
    }
}
